package jsp.servlet;


import jsp.model.User;
import jsp.servcie.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet({"/userList"})
public class UserListServlet extends HttpServlet {

    UserService service = new UserService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        List<User> list = service.list();
        request.setAttribute("list", list);
        request.getRequestDispatcher(request.getContextPath() + "/userList.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");

        String id = request.getParameter("id");
        String name = request.getParameter("name");
        User user = new User();
        user.setName(name);
        if (id != null && !id.isEmpty()) {
            user.setId(Integer.parseInt(id));
        }

        List<User> list = service.list(user);

        request.setAttribute("id", id);
        request.setAttribute("name", name);
        request.setAttribute("list", list);
        request.getRequestDispatcher(request.getContextPath() + "/userList.jsp").forward(request, response);
    }
}
